package utils

import (
	"bytes"
	"fmt"
	"math/rand"
	"os"
	"time"
)

//生成一个随机数
func RandChar(size int) string {
	char := "abcd67efijkABCDEFJKLMlmnopqrs89tuvwxyzNOPQRghSTUVWXYZ012GHI345"
	rand.Seed(time.Now().UnixNano()) // 产生随机种子
	var s bytes.Buffer
	for i := 0; i < size; i++ {
		s.WriteByte(char[rand.Int63()%int64(len(char))])
	}
	return s.String()
}

//当前时间
func GetNowTimeStr() string {
	return time.Unix(time.Now().Unix(), 0).Format("2006-01-02 15:04:05")
}

//写入日志
//由logrus代替，后期删除
var LogUrl = ""

func WriteLog(fileurl, str string) {
	f, err := os.OpenFile(fileurl, os.O_CREATE|os.O_APPEND, 0600)
	defer f.Close()
	if err != nil {
		fmt.Println(err.Error())
	} else {
		t := time.Now() //2019-07-31 13:55:21.3410012 +0800 CST m=+0.006015601
		_, err = f.Write([]byte(t.Format("2006-01-02 15:04:05") + " " + str + "\n"))
		CheckErr(err)
	}
}

func WriteLogV2(str string) {
	fileurl := ""
	if LogUrl == "" {
		fileurl = "run.log"
	} else {
		fileurl = LogUrl
	}
	f, err := os.OpenFile(fileurl, os.O_CREATE|os.O_APPEND, 0600)
	defer f.Close()
	if err != nil {
		fmt.Println(err.Error())
	} else {
		t := time.Now() //2019-07-31 13:55:21.3410012 +0800 CST m=+0.006015601
		_, err = f.Write([]byte(t.Format("2006-01-02 15:04:05") + " " + str + "\n"))
		CheckErr(err)
	}
}
